package info.niwota.start.help;

import info.niwota.start.Debug;
import info.niwota.start.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class WebViewActivity extends Activity {

	class WebChrome extends WebChromeClient {

		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
					newProgress * 100);
			if (newProgress == 100) {
				CookieSyncManager.getInstance().sync();
			}
		}

		@Override
		public void onReceivedTitle(WebView view, String title) {
			WebViewActivity.this.setTitle(title);
		}
	}

	private static final String LOG_TAG = "WebViewActivity";

	private static final String INDEX_PAGE = "file:///android_asset/index.html";;

	private WebView webview;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		CookieSyncManager.createInstance(this);

		requestWindowFeature(Window.FEATURE_PROGRESS);
		requestWindowFeature(Window.FEATURE_LEFT_ICON);

		webview = new WebView(this);
		setContentView(webview);

		getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
				R.drawable.icon25);

		webview.setWebChromeClient(new WebChrome());
		//
		WebSettings s = webview.getSettings();
		
		s.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
		s.setUseWideViewPort(true);
		s.setSavePassword(false);
		s.setSaveFormData(false);

		s.setJavaScriptEnabled(false);

		if (savedInstanceState != null) {
			webview.restoreState(savedInstanceState);
		} else {
			Intent i = getIntent();
			if (i.getData() != null) {
				Uri uri = i.getData();
				//
				if (Debug.DEBUG) {
					Log.d(LOG_TAG, "uri: " + uri);
				}
				webview.loadUrl(uri.toString() + "?" + i.getType());
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		webview.destroy();
	}

	@Override
	protected void onResume() {
		super.onResume();
		CookieSyncManager.getInstance().startSync();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		webview.saveState(outState);
	}

	@Override
	protected void onStop() {
		super.onStop();

		CookieSyncManager.getInstance().stopSync();
		webview.stopLoading();
	}

	public static void help(Context ctx) {
		help(ctx, INDEX_PAGE);
	}

	public static void help(Context ctx, String uri) {
		try {
			Intent i = new Intent(ctx, WebViewActivity.class);
			i.setData(Uri.parse(uri));
			ctx.startActivity(i);
		} catch (Exception e) {
			if (Debug.DEBUG) {
				e.printStackTrace();
			}
		}
	}

}
